package com.culture.bootdemo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.Feature;
import com.culture.bootdemo.model.dto.StrDTO;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: wen
 * @DateTime: 2023/11/22 20:04
 * @Description:
 **/
public class JsonDemo {

    /**
     * json转list(指定属性)
     */
    public static void strjson2List() {
        String s = "[ { \"name\":\"02:00-04:00\", \"value\":5464353 }, { \"name\":\"00:00-02:00\", \"value\":5534 }, { \"name\":\"04:00-06:00\", \"value\":300000 }, { \"name\":\"08:00-10:00\", \"value\":40000 }, { \"name\":\"14:00-16:00\", \"value\":35334 }, { \"name\":\"12:00-14:00\", \"value\":50000 }, { \"name\":\"16:00-18:00\", \"value\":7854545 }, { \"name\":\"18:00-20:00\", \"value\":78545 }, { \"name\":\"20:00-22:00\", \"value\":8578 },{\"name\":\"22:00-23:00\", \"value\":4334}]";
        //方式一:fastjson
        List<StrDTO> demoVOS = JSON.parseArray(s, StrDTO.class);
        System.out.println(demoVOS);
        //list根据某个字段排序
        List<StrDTO> collect = demoVOS.stream().sorted(Comparator.comparing(StrDTO::getName)).collect(Collectors.toList());
        System.out.println("collect=" + collect);

        //方式二：gson
        Gson gson = new Gson();
        List<StrDTO> list = gson.fromJson(s, new TypeToken<List<StrDTO>>() {
        }.getType());
        System.out.println("gson:" + list);
    }

    /**
     * json转map （指定泛型）
     * Feature.OrderedField：保持原json顺序
     */
    public static void strjson2Map() {
        String jsonstr = "{\"hour\":{\"metrics\":[\"zszf_my\",\"zszf_sfje\"],\"thb\":[\"hb\",\"tbWeek\",\"tbYear\"]},\"day\":{\"metrics\":[\"zszf_my\",\"zszf_sfje\"],\"thb\":[\"hb\",\"tbWeek\",\"tbYear\"]},\"week\":{\"metrics\":[\"zszf_my\",\"zszf_sfje\"],\"thb\":[\"hb\"]},\"month\":{\"metrics\":[\"zszf_my\"],\"thb\":[\"hb\",\"tbYear\"]}}";

        //方式一：fastjson TypeReference
        Map<String, Map<String, List<String>>> map1 =
                JSON.parseObject(jsonstr, new TypeReference<Map<String, Map<String, List<String>>>>() {
                }, Feature.OrderedField);

        System.out.println("map1=" + map1);

        //方式二：
//        Gson gson = new Gson();
        Map<String, Map<String, List<String>>> map2 = new Gson().fromJson(jsonstr, new TypeToken<Map<String, Map<String, List<String>>>>() {
        }.getType());

        System.out.println("map2=" + map2);

    }


    public static void main(String[] args) {
        strjson2Map();
    }
}
